<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="600px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="150px">
      <el-form-item label="合同编号" prop="contractCode">
        <el-input v-model="form.contractCode" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="form.contractName" style="width: 370px;"/>
      </el-form-item>
       <el-form-item label="所属客户" prop="customerId" >
       <el-select v-model="form.customerId" placeholder="所属客户" v-on:change="indexSelect($event)" style="width: 370px;">
           <el-option v-for="(item,index) in customerItem" :key="index" :label="item.customerName" :value="item.id">
           </el-option>
      </el-select>
      </el-form-item>
       <el-form-item label="合同类型" prop="contractItemId">
       <el-select v-model="form.contractItemId" placeholder="合同类型" v-on:change="indexSelect($event)">
           <el-option v-for="(item,index) in contTypeItem" :key="index" :label="item.label" :value="item.id">
           </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="合同内容" prop="contractContent">
        <el-input v-model="form.contractContent" style="width: 370px;"/>
      </el-form-item>
     

      <!-- <el-form-item label="合同类型*id" >
        <el-input v-model="form.contractItemId" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="合同类型*名称" >
        <el-input v-model="form.contractItemName" style="width: 370px;"/>
      </el-form-item> -->
      <!-- <el-form-item label="所属客户id" >
        <el-input v-model="form.customerId" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="所属客户" >
        <el-input v-model="form.customerName" style="width: 370px;"/>
      </el-form-item> -->
          <el-form-item label="合同开始时间" prop="startTime">
        <el-date-picker
          style="width: 230px"
          type="datetime"
          placeholder="请选择"
          v-model="form.startTime"
          @change="startTimeChange"
          :format="'yyyy-MM-dd'"
          :picker-options="startTimeConfig">
      </el-date-picker>
        <!-- <el-input v-model="form.startTime" style="width: 370px;"/> -->
      </el-form-item>
      <el-form-item label="合同结束时间" prop="endTime">
        <el-date-picker
          style="width: 230px"
          type="datetime"
          placeholder="请选择"
          v-model="form.endTime"
          @change="endTimeChange"
          :format="'yyyy-MM-dd'"
          :picker-options="endTimeConfig">
      </el-date-picker>
        <!-- <el-input v-model="form.endTime" style="width: 370px;"/> -->
      </el-form-item>

       <el-form-item label="合同签订时间" prop="creatTime">
        <el-date-picker
          style="width: 230px"
          type="datetime"
          placeholder="请选择"
          v-model="form.creatTime"
          @change="creatTimeChange"
          :format="'yyyy-MM-dd'"
          :picker-options="creatTimeConfig">
      </el-date-picker>
        <!-- <el-input v-model="form.endTime" style="width: 370px;"/> -->
      </el-form-item>

      <!-- <el-form-item label="合同开始时间" >
        <el-input v-model="form.startTime" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="合同结束时间" >
        <el-input v-model="form.endTime" style="width: 370px;"/>
      </el-form-item> -->
      <!-- <el-form-item label="合同签订时间" >
        <el-input v-model="form.creatTime" style="width: 370px;"/>
      </el-form-item> -->
       <el-form-item label="合同金额（元）" prop="contractMoney">
        <el-input v-model="form.contractMoney" style="width: 370px;"/>
      </el-form-item> 
      <el-form-item label="附件" >
        <el-upload
      :before-remove="handleBeforeRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-preview="handlePreview"
      :file-list="fileList"
      :headers="headers"
      :action="imagesUploadApi"
      class="upload-demo"
      multiple>
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" style="display: block;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
    </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" v-show="isView===true" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { add, edit } from '@/api/tCustomerContract'
import { mapGetters } from 'vuex'
import { del } from '@/api/qiniu'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    sup_this: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
       headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      loading: false, dialog: false,
      form: {
        id: '',
        contractCode: '',
        attachments: '',
        contractName: '',
        contractContent: '',
        contractItemId: '',
        contractItemName: '',
        customerId: '',
        customerName: '',
        startTime: '',
        endTime: '',
        creatTime: '',
        contractMoney: ''
      },
      contTypeItem:[],
      customerItem:[],
      fileList: [],
      files: [],
     rules: {
        contractCode: [
          { required: true, message: "请输入合同编号", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "请输入合同名称", trigger: "blur" }
        ],
        contractContent: [
          { required: true, message: "请输入合同内容", trigger: "blur" }
        ],
        contractItemId: [
          { required: true, message: "请选择合同类型", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "请选择所属客户", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请输入合同开始时间", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "请输入合同结束时间", trigger: "blur" }
        ],
        creatTime: [
          { required: true, message: "请输入合同签订时间", trigger: "blur" }
        ],
        contractMoney: [
          { required: true, message: "请输入合同金额", trigger: "blur" }
        ]
      }
    }
  },
  mounted:function(){
     this.byNameinfo("合同类型");
     this.tcustmerInfoAll();
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  methods: {

    //日期S
        initTimeConfig () {
          let self = this
          // 开始时间配置
          this.startTimeConfig = {
              disabledDate (time) {
                  if (self.realTimeInfo.endTime) {
                      return time.getTime() > new 
                      Date(self.realTimeInfo.endTime).getTime()
                  }
              }
          },
          // 结束时间配置
          this.endTimeConfig = {
              disabledDate (time) {
                  if (self.realTimeInfo.startTime) {
                      return time.getTime() < new 
                      Date(self.realTimeInfo.startTime).getTime()
                  }
              }
          }
          this.creatTimeConfig = {
              disabledDate (time) {
                  if (self.realTimeInfo.creatTime) {
                      return time.getTime() < new 
                      Date(self.realTimeInfo.creatTime).getTime()
                  }
              }
          }
          
      },
      startTimeChange (val) {
          this.realTimeInfo.startTime = val
      },
      endTimeChange (val) {
          this.realTimeInfo.endTime = val
      },
     creatTimeChange (val) {
          this.realTimeInfo.creatTime = val
      },
      
    //--------------------------
     tcustmerInfoAll(){
        this.getAllcustmer().then(res => {
          this.customerItem=res;
        //根据id再进行全部查询
      })
    },
    getAllcustmer() {
      return request({
        url: 'api/tCustomerInfoAll',
        method: 'get'
      })
    },
    byNameinfo(name) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
           this.contTypeItem=resobject;
        //根据id再进行全部查询
      })
        //根据id再进行全部查询
      })
    },
        // 获取id值
    byName(name) {
      return request({
        url: 'api/dict/byName/' + name,
        method: 'get'
      })
    },
        // 获取id值
    bydictId(id) {
      return request({
        url: 'api/dictDetail/findByDeptId/' + id,
        method: 'get'
      })
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;

           const fileIds = []
          this.files.forEach(function(data, index) {
            fileIds.push(data.id)
          })
          this.form.attachments = fileIds.join(',')
          if (this.isAdd) {
            this.doAdd();
          } else this.doEdit();
        } else {
          return false;
        }
      });
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        contractCode: '',
        attachments: '',
        contractName: '',
        contractContent: '',
        contractItemId: '',
        contractItemName: '',
        customerId: '',
        customerName: '',
        startTime: '',
        endTime: '',
        creatTime: '',
        contractMoney: ''
      }
    },
        handlePreview(file) {
      document.location.href = file.url
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.files.push({ uid, id })
    },
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].uid === file.uid) {
          del(this.files[i].id).then(res => { 
            _this.pictures.splice(i,1)
          })
          return true
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 刷新列表数据
    // doSubmit() {
    //   this.fileList = []
    //   this.dialogVisible = false
    //   this.dialogImageUrl = ''
    //   this.dialog = false
    //   this.$parent.$parent.init()
    // },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>

</style>
